package aszm.chahaospider.parser.chahao;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import aszm.chahaospider.utils.MybatisUtils;
import aszm.chahaospider.utils.Utils;
import chaohao.mybatis.dao.ProviceDtoMapper;
import chaohao.mybatis.model.ProviceDto;

public class ProviceParser {
	private static final Logger Log = Logger.getLogger(ProviceParser.class.getName());

	public static List<ProviceDto> getProviceFromWeb(String url, boolean writeDb) {
		Document doc = Utils.getDocumentDoc(url);
		Elements links = doc.select("h1 a");
		List<ProviceDto> provices = parserProvice(links);
		if (writeDb) {
			Log.info(links.size() + "开始写入 provices ……");
			createFile(links);
		}
		return provices;
	}

	public static List<ProviceDto> parserProvice(Elements links) {
		List<ProviceDto> proviceUrl = new ArrayList<ProviceDto>();
		for (Element link : links) {
			proviceUrl.add(parser(link));
		}
		Log.info(links.size() + "条 provices 解析成功！");
		return proviceUrl;
	}

	/**
	 * 从数据库查询
	 * 
	 * @return
	 */
	public static List<ProviceDto> getProviceFromDB() {
		SqlSession session = MybatisUtils.getSqlSession();
		List<ProviceDto> provices = session.getMapper(ProviceDtoMapper.class).selectAll();
		session.close();
		return provices;
	}

	/**
	 * 解析省份节点
	 * 
	 * @param provice
	 * @return
	 */
	public static ProviceDto parser(Element provice) {
		ProviceDto tb_Provice = new ProviceDto();
		tb_Provice.setName(provice.html());
		tb_Provice.setUrl(provice.attr("href"));
		Log.info(tb_Provice.toString());
		return tb_Provice;
	}

	/**
	 * 持久化数据
	 * 
	 * @param provices
	 */
	public static void createFile(List<Element> provices) {
		SqlSession session = MybatisUtils.getSqlSession();
		int count = 0;
		for (Element element : provices) {
			ProviceDto provice = parser(element);
			int result = session.getMapper(ProviceDtoMapper.class).insert(provice);
			count += result;
		}
		session.commit();
		MybatisUtils.showMessages(MybatisUtils.CRUD_Enum.Add, count);
	}
}
